# coding: utf-8
# Author: Legend奇
# @Time： 2020/7/21 下午3:31
import re
__all__ = [
    'underline2hump',
    'create_model',
           ]


def underline2hump(underline_str, first=True):
    """
    下划线形式字符串转成驼峰形式
    :param first: 是否将首字母转为大写
    :param underline_str: 下划线形式字符串
    :return: 驼峰形式字符串
    """
    # 这里re.sub()函数第二个替换参数用到了一个匿名回调函数，回调函数的参数x为一个匹配对象，返回值为一个处理后的字符串
    sub = re.sub(r'(_\w)', lambda x: x.group(1)[1].upper(), underline_str)
    if first:
        sub = list(sub)
        sub[0] = sub[0].upper()
        sub = ''.join(sub)
    return sub


def create_model(name, abstract_class, fields, meta_options=None):
    class Meta:
        pass

    if meta_options is not None:
        for key, value in meta_options.items():
            setattr(Meta, key, value)

    attrs = {'__module__': abstract_class.__module__, 'Meta': Meta}

    for _name, attr in fields.items():
        attrs[_name] = attr

    model = type(name, (abstract_class,), attrs)

    return model
